<template>
  <div>
    <el-dialog title="商品新增" :visible.sync="editVisible" width="84%">
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="商品图（单张）">
          <el-upload
            ref="productImg"
            :limit="1"
            action="#"
            list-type="picture-card"
            :auto-upload="false"
          >
            <i slot="default" class="el-icon-plus"></i>
            <div slot="file" slot-scope="{ file }">
              <img
                class="el-upload-list__item-thumbnail"
                :src="file.url"
                alt=""
              />
              <span class="el-upload-list__item-actions">
                <span
                  class="el-upload-list__item-preview"
                  @click="handlePictureCardPreview(file)"
                >
                  <i class="el-icon-zoom-in"></i>
                </span>
                <span
                  class="el-upload-list__item-delete"
                  @click="handleRemove(file)"
                >
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number
            v-model="form.price"
            :min="1"
            :max="99999999"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="主类型">
          <el-checkbox-group v-model="form.mainType">
            <el-checkbox v-for="item in mainType" :label="item" :key="item">{{
              item
            }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="次类型">
          <el-checkbox-group v-model="form.secondType">
            <el-checkbox v-for="item in secondType" :label="item" :key="item">{{
              item
            }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="大轮播图">
          <el-upload
            ref="rotationBig"
            :limit="99"
            :multiple="true"
            action="#"
            list-type="picture-card"
            :auto-upload="false"
          >
            <i slot="default" class="el-icon-plus"></i>
            <div slot="file" slot-scope="{ file }">
              <img
                class="el-upload-list__item-thumbnail"
                :src="file.url"
                alt=""
              />
              <span class="el-upload-list__item-actions">
                <span
                  class="el-upload-list__item-preview"
                  @click="handlePictureCardPreview(file)"
                >
                  <i class="el-icon-zoom-in"></i>
                </span>
                <span
                  class="el-upload-list__item-delete"
                  @click="ratationBigRemove(file)"
                >
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="小轮播图">
          <el-upload
            ref="rotationSmall"
            :limit="99"
            action="#"
            :multiple="true"
            list-type="picture-card"
            :auto-upload="false"
          >
            <i slot="default" class="el-icon-plus"></i>
            <div slot="file" slot-scope="{ file }">
              <img
                class="el-upload-list__item-thumbnail"
                :src="file.url"
                alt=""
              />
              <span class="el-upload-list__item-actions">
                <span
                  class="el-upload-list__item-preview"
                  @click="handlePictureCardPreview(file)"
                >
                  <i class="el-icon-zoom-in"></i>
                </span>
                <span
                  class="el-upload-list__item-delete"
                  @click="ratationSmallRemove(file)"
                >
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品介绍(数组格式)" prop="introduce">
          <el-input v-model="form.introduce"></el-input>
        </el-form-item>
        <el-form-item label="商品信息(json格式)">
          <el-input v-model="form.info"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" @click="editSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 商品图 -->
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="previewUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import generateUUID from "../../utils/generateUUID";
export default {
  name: "edit",
  data() {
    return {
      editVisible: false,
      form: {
        name: "",
        price: 0,
        mainType: [],
        secondType: [],
        introduce: "",
        info: "",
      },
      dialogVisible: false,
      previewUrl: "",
      mainType: [
        "茶包",
        "熏香",
        "知览茶",
        "支持花呗",
        "甜品",
        "茶具、陶器、瓶子",
      ],
      secondType: [
        "焙茶",
        "金平糖",
        "煎茶",
        "瓶子",
        "玄米茶",
        "木茶",
        "红茶",
        "抹茶",
        "茶器",
        "烤点心",
        "冰淇淋",
      ],

      rules: {
        name: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
        price: [{ required: true, message: "请输入价格", trigger: "blur" }],
        introduce: [
          { required: true, message: "请输入商品简介", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    //   编辑模式下，渲染商品的初始数据
    render(row) {
      console.log(row);
      this.form.name = row.name;
      this.form.price = row.price;
      this.form.info = row.info;
      this.form.introduce = row.introduce;

      // 商品图渲染
      this.$refs.productImg.uploadFiles = [];
      this.axios.get(row.img_url, { responseType: "blob" }).then((response) => {
        if (response.status === 200 && response) {
          const productImg = this.getImg(response);
          this.$refs.productImg.uploadFiles.push(productImg);
        }
      });

      // 渲染大轮播图
      const imgBigUrls = Array.from(row.imgBigUrls);
      this.$refs.rotationBig.uploadFiles = [];
      for (let i in imgBigUrls) {
        const url = imgBigUrls[i];
        console.log(url);
        this.axios
          .get(url, { responseType: "blob" })
          .then((response) => {
            if (response.status === 200 && response) {
              const productImg = this.getImg(response);
              this.$refs.rotationBig.uploadFiles.push(productImg);
            }
          });
      }
    }, // render
    editSubmit() {
      var fd = new FormData();
      fd.append("name", this.form.name);
      fd.append("price", this.form.price);
      fd.append("mainType", this.form.mainType);
      fd.append("secondType", this.form.secondType);
      fd.append("introduce", this.form.introduce);
      fd.append("info", this.form.info);

      for (let i in this.$refs.rotationBig.uploadFiles) {
        let item = this.$refs.rotationBig.uploadFiles[i].raw;
        fd.append("rotationBig", item);
      }

      for (let i in this.$refs.rotationSmall.uploadFiles) {
        let item = this.$refs.rotationSmall.uploadFiles[i].raw;
        fd.append("rotationSmall", item);
      }

      fd.append("productImg", this.$refs.productImg.uploadFiles[0].raw);

      let config = {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      };
      this.axios.post("/product/addOne", fd, config).then((response) => {
        console.log(response);
      });
    }, // getProduct
    handleRemove(file) {
      // 加slot后删除会失效，手动加删除
      this.$refs.productImg.uploadFiles =
        this.$refs.productImg.uploadFiles.filter((item) => {
          if (item.url === file.url) return false;
          return true;
        });
    }, // handleRemove
    handlePictureCardPreview(file) {
      this.previewUrl = file.url;
      this.dialogVisible = true;
    },
    ratationBigRemove(file) {
      this.$refs.rotationBig.uploadFiles =
        this.$refs.rotationBig.uploadFiles.filter((item) => {
          if (item.url === file.url) return false;
          return true;
        });
    }, // ratationBigRemove
    ratationSmallRemove(file) {
      this.$refs.rotationSmall.uploadFiles =
        this.$refs.rotationSmall.uploadFiles.filter((item) => {
          if (item.url === file.url) return false;
          return true;
        });
    }, // ratationSmallRemove
    // 生成 uuid，网上抄的
    
    // 编辑模式下，向服务器获取图片数据, 返回的是上传组件中 uploadFiles 的格式
    getImg(response) {
      //这里没有用ajax当时用ajax出现了问题就用了原生发请求
      if (!(response.status === 200 && response)) {
        return false;
      }
      const uuid = generateUUID();
      const blob = new Blob([response.data], { type: "image/jpg" });
      const blobUrl = URL.createObjectURL(blob);
      const file = new window.File([blob], uuid, {
        type: "image/jpg",
      });

      const uploadFile = {
        status: "ready",
        size: blob.size,
        name: uuid + ".jpg",
        uid: uuid,
        url: blobUrl,
        raw: file,
      };

      return uploadFile;
    },
  }, // methods
  mounted() {},
};
</script>

<style>
</style>